package com.gxa.eshops.portal.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.eshops.portal.entity.domain.Goods;
import com.gxa.eshops.portal.repository.GoodsRepository;
import com.gxa.eshops.portal.service.GoodsService;
import com.gxa.eshops.portal.service.impl.GoodsCacheServiceImpl;
import com.gxa.eshps.cores.common.JsonResult;
import com.gxa.eshps.cores.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import java.util.Map;
import java.util.Random;

/**
 * @program: IntelliJ IDEA
 * @description:
 * @author: Mr.Wang
 * @create: 2022-07-07 14:20
 **/
@RestController
@Validated
@RequestMapping("/goods")
@Api(tags = "商品接口")
public class GoodsController {
    @Autowired
    GoodsService goodsService;
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    RedisTemplate<String ,Object> redisTemplate;
    @Autowired
    GoodsCacheServiceImpl goodsCacheService;

    @PostMapping("/secondKill")
    @ApiOperation("商品秒杀")
    public Map<String ,Object> secondKill(Long id) throws BusinessException {
        Boolean success = goodsService.secondKill(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        if (success) {
            jsonResult.setMsg("秒杀成功");
        } else {
            jsonResult.setMsg("秒杀失败");
        }
        return jsonResult.getMap();
    }
    @PostMapping("/selectGoodsById")
    @ApiOperation("错误接口")
    public Map<String ,Object> selectGoodsById(Long goodsId) throws JsonProcessingException {
        //默认从redis获取商品信息
        Object redisGoods = redisTemplate.opsForValue().get(goodsId.toString());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        //判断redis读取的信息有值则直接返回
        if (redisGoods!=null){
            jsonResult.setData(redisGoods);
            System.out.println("redis获取商品:"+ redisGoods);
        } else {
            //redis没有,则从MySQL获取,写入redis并返回
            Goods mysqlGoods = goodsRepository.findGoodsByGoodsId(goodsId);
            ObjectMapper objectMapper = new ObjectMapper();
            //转换为JSON存入redis
            String asString = objectMapper.writeValueAsString(mysqlGoods);
            redisTemplate.opsForValue().set(goodsId.toString(),asString);
            jsonResult.setData(asString);
            System.out.println("MySQL获取商品:"+mysqlGoods);
        }
        return jsonResult.getMap();
    }
    @PostMapping("/getRedEnvelopes")
    @ApiOperation("随机红包")
    public Map<String ,Object> getRedEnvelopes(@RequestParam @Min(1) Integer num, @RequestParam @Pattern(regexp = "^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$") String money){
        JsonResult jsonResult = new JsonResult();
        Double[] redEnvelopes = new Double[num];
        double moneys = Double.parseDouble(money);
        double compare = moneys;
        //平均金额
        double avg = (moneys-0.01*num)/num;
        //每人的金额在平均值的[0,1)倍,保底0.01元
        for (int i = 0; i < num;i++){
            String format = String.format("%.2f", Math.random() * avg*1.3 + 0.01);
            redEnvelopes[i] = Double.parseDouble(format);
        }
        //剩余金额
        for (Double redEnv:redEnvelopes
             ) {
            moneys -= redEnv;
        }
        //moneys保留2位小数,剩余金额的处理
        String syAvg = String.format("%.2f", moneys / num);
        double syDouble = Double.parseDouble(syAvg);
        for (int i = 0; i < num-1; i++){
            //精确度处理
            redEnvelopes[i] += syDouble;
            String format = String.format("%.2f", redEnvelopes[i]);
            redEnvelopes[i] = Double.parseDouble(format);
        }
        //验证红包总金额,总金额处理
        double sum = 0.00;
        for (Double red:redEnvelopes
             ) {
            sum += red;
        }
        //精确度处理,保证总金额一致
        String format = String.format("%.2f", sum);
        //sum总红包金额
        double aDouble = Double.parseDouble(format);
        int anInt = new Random().nextInt(num);
        double total = 0.00;
        if (compare>aDouble){
            redEnvelopes[anInt] += (compare - aDouble);
            String format1 = String.format("%.2f", redEnvelopes[anInt]);
            redEnvelopes[anInt] = Double.parseDouble(format1);
            for (Double reds:redEnvelopes
            ) {
                total += reds;
            }
        }
        String format1 = String.format("%.2f", total);
        total = Double.parseDouble(format1);
        System.out.println("总金额:"+total+"  "+compare);

        jsonResult.setCode("1");
        jsonResult.setMsg("红包已生成");
        jsonResult.setData(redEnvelopes);
        return jsonResult.getMap();
    }
    @PostMapping("/getGoodsById")
    @ApiOperation("查询商品信息byID")
    public Map<String,Object> getGoodsById(Long id) throws Exception {
        Object goods = goodsCacheService.selectGoodsCache(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(goods);
        return jsonResult.getMap();
    }
}
